# -*- encoding: utf-8 -*-

from google.appengine.api import users

from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponseRedirect, Http404
from django.utils.translation import ugettext as _

from users import login_required, admin_required
from sport_metrics import get_context
from sport_metrics.models import SportMetricsView, properties

def get_sport_definition_form(data=None, initial_name='', initial_choice=[]):
    from metrics.models import properties
    class SportDefinitionForm(forms.Form):
        name = forms.CharField(label=_(u'Name'),
                               required=True,
                               min_length=2,
                               help_text=_(u'Name of the sport in English'),
                               initial=initial_name)
        metrics = forms.MultipleChoiceField(label=_(u'Metrics'),
                                            required=True,
                                            choices=properties.formated_data(),
                                            initial = initial_choice)

    return SportDefinitionForm(data)

@login_required
@admin_required
def create_sport(request):
    """Create a sport metric view. This is done by choosing the name of the sport, and all
    the property needed to have interesting measure of performance in this sport."""
    name_not_unique = False
    if request.method == 'POST':
        form = get_sport_definition_form(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            name = data['name']
            try:
                metrics_view = SportMetricsView(key_name=name,
                                                name=name,
                                                metrics_properties=data['metrics'])
                metrics_view.put()
                return HttpResponseRedirect('/')
            except SportMetricsView.NameMustBeUnique:
                name_not_unique = True
    else:
        form = get_sport_definition_form()
    return render_to_response('sport_metrics/create_sport.html', 
                              {'form':form,
                               'name_not_unique':name_not_unique},
                              get_context())

@login_required
@admin_required
def edit_sport(request, sport_key):
    sport_metrics_view = SportMetricsView.get_by_key_name(sport_key)
    if not sport_metrics_view:
        raise Http404
    if request.method == 'POST':
        metrics_list = [metrics.strip() for metrics in request.POST['metrics'].split(',')]
        for metrics in metrics_list:
            if metrics not in properties.properties:
                raise Http404
        sport_metrics_view.metrics_properties = metrics_list
        sport_metrics_view.put(False)
    else:
        metrics_list = sport_metrics_view.metrics_properties
    return render_to_response('sport_metrics/edit_sport.html', 
                              {'name':sport_metrics_view.name,
                               'metrics_list':(', '.join(metrics_list))},
                              get_context())



def get_forms(request, metrics_view, all_metrics):
    """Retun a list of form for the view if there is suitable forms.
    In the case where the request is a POST, the function return None if the forms should
    not be shown and the page should be reloaded instead"""
    from metrics.forms import DateForm
    all_forms = []
    date = None
    if request.method == 'POST':
        dateform = DateForm(request.POST,
                            prefix='date')
        if dateform.is_valid():
            all_forms.append(DateForm(prefix='date'))
            date = dateform.cleaned_data['date']
        else:
            all_forms.append(dateform)
    else:
        all_forms.append(DateForm(prefix='date'))

    user = users.get_current_user()
    all_valid = True
    for metrics in all_metrics:
        result = True
        if request.method == 'POST' and date:
            result, form = metrics.add_data(user,
                                            date,
                                            metrics_view,
                                            request.POST)
            all_valid = result and all_valid
        if result:
            all_forms.append(metrics.get_form())
        else:
            all_forms.append(form)

    if not(request.method == 'POST' and date and all_valid):
        return all_forms

def get_charts(all_metrics, metrics_view):
    """Return a list of dict with the name of the data, and url of the chart's image.
    e.g. [{'name':u'coucou', 'chart_url':'http://www.ikipou.com'}]"""
    all_data = []
    for metrics in all_metrics:
        name = metrics.get_name()
        chart_image = metrics.get_chart_url(users.get_current_user(), metrics_view)
        all_data.append({'name':name, 
                         'chart_url':chart_image})
    return all_data

def sport_metrics(request, sport_key):
    sport_metrics_view = SportMetricsView.get_by_key_name(sport_key)
    if not sport_metrics_view:
        raise Http404
    sport_name = _(sport_metrics_view.name)
    all_metrics = [properties.class_for_name(name) for name in sport_metrics_view.metrics_properties]

    all_forms = get_forms(request, sport_metrics_view, all_metrics)
    if not all_forms:
        return HttpResponseRedirect('.')

    all_chart_data = get_charts(all_metrics, sport_metrics_view)

    return render_to_response('sport_metrics/sport_metrics.html',
                              {'sport_name':sport_name, 
                               'forms':all_forms,
                               'charts_data':all_chart_data},
                              get_context())
    
